<template>
    <view class="page">
        <view class="container">
            <scroll-view scroll-y class="scroll-view" enable-back-to-top>
                <view class="cart-header">
                    <text class="clear-cart" @click="clearCart">清空购物车</text>
                </view>
                <view class="store-list">
                    <view v-for="(store) in groupedCartItems" :key="store.storeId" class="store-item">
                        <view class="store-header">
                            <view class="store-select">
                                <checkbox :checked="store.isSelected" @click="toggleStoreSelect(store)"/>
                                <text class="select-text">全选</text>
                            </view>
                            <text class="store-name">{{store.storeName}}</text>
                        </view>
                        <view class="goods-list">
                            <view v-for="(item, index) in store.goods" :key="index" class="goods-item">
                                <view class="item-left">
                                    <checkbox :checked="item.isSelected" @click="toggleSelect(item, store)"/>
                                    <image :src="`/static/${item.imgUrl}`" class="goods-image"></image>
                                </view>
                                <view class="item-right">
                                    <view class="goods-info">
                                        <text class="goods-name">{{item.name}}</text>
                                        <text class="goods-sales">月售{{item.sales}}件</text>
                                        <view class="price-box">
                                            <text class="current-price">¥{{item.price}}</text>
                                            <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                                        </view>
                                    </view>
                                    <view class="stepper">
                                        <text class="btn minus" @click="decreaseQuantity(item)">-</text>
                                        <text class="number">{{item.quantity}}</text>
                                        <text class="btn plus" @click="increaseQuantity(item)">+</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="store-footer" v-if="store.goods.length > 0">
                            <view class="footer-left">
                                <text class="total-text">合计：</text>
                                <text class="total-price">¥{{getStoreTotal(store).toFixed(2)}}</text>
                            </view>
                            <button class="submit-btn" @click="handleStoreCheckout(store)">
                                去结算({{getStoreSelectedCount(store)}})
                            </button>
                        </view>
                    </view>
                </view>
                <view v-if="totalCount === 0" class="empty-cart">
                    <image src="/static/images/empty-cart.png" class="empty-img"></image>
                    <text class="empty-text">购物车空空的~~</text>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            groupedCartItems: [],
            phoneNumber: '' // 存储手机号
        };
    },
    computed: {
        totalCount() {
            return this.groupedCartItems.reduce((total, store) =>
                total + store.goods.length, 0);
        },
        selectedCount() {
            return this.groupedCartItems.reduce((total, store) => 
                total + store.goods.filter(item => item.isSelected).length, 0);
        },
        totalPrice() {
            return this.groupedCartItems.reduce((total, store) => {
                return total + store.goods
                   .filter(item => item.isSelected)
                   .reduce((sum, item) => sum + (item.price * item.quantity), 0);
            }, 0);
        }
    },
    onShow() {
        this.phoneNumber = uni.getStorageSync('currentPhone'); // 获取当前登录用户的手机号
        this.loadCartItems();
    },
    methods: {
        loadCartItems() {
            const allItems = uni.getStorageSync('cartItems') || [];
            const userItems = allItems.filter(item => item.phoneNumber === this.phoneNumber);

            const groupedItems = {};
            userItems.forEach(item => {
                if (!groupedItems[item.storeId]) {
                    groupedItems[item.storeId] = {
                        storeId: item.storeId,
                        storeName: item.storeName,
                        isSelected: false,
                        goods: []
                    };
                }
                groupedItems[item.storeId].goods.push({
                   ...item,
                    isSelected: item.isSelected || false
                });
            });

            this.groupedCartItems = Object.values(groupedItems);
        },
        toggleSelect(item, store) {
            item.isSelected =!item.isSelected;
            store.isSelected = store.goods.every(item => item.isSelected);
            this.updateCart();
        },
        toggleStoreSelect(store) {
            store.isSelected =!store.isSelected;
            store.goods.forEach(item => {
                item.isSelected = store.isSelected;
            });
            this.updateCart();
        },
        updateCart() {
            const flatItems = this.groupedCartItems.reduce((items, store) => {
                return items.concat(store.goods);
            }, []);
            const allItems = uni.getStorageSync('cartItems') || [];
            const otherUserItems = allItems.filter(item => item.phoneNumber!== this.phoneNumber);
            const newAllItems = [...otherUserItems, ...flatItems];
            uni.setStorageSync('cartItems', newAllItems);
        },
        increaseQuantity(item) {
            item.quantity++;
            this.updateCart();
        },
        decreaseQuantity(item) {
            if (item.quantity > 1) {
                item.quantity--;
            } else {
                this.removeItem(item);
            }
            this.updateCart();
        },
        removeItem(item) {
            uni.showModal({
                title: '提示',
                content: '确定要删除该商品吗？',
                success: (res) => {
                    if (res.confirm) {
                        const index = this.groupedCartItems.findIndex(store => 
                            store.goods.some(i => i._id === item._id));
                        if (index!== -1) {
                            const store = this.groupedCartItems[index];
                            const goodsIndex = store.goods.findIndex(i => i._id === item._id);
                            if (goodsIndex!== -1) {
                                store.goods.splice(goodsIndex, 1);
                            }
                            this.updateCart();
                        }
                    }
                }
            });
        },
        clearCart() {
            if (this.totalCount === 0) return;
            uni.showModal({
                title: '提示',
                content: '确定要清空购物车吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.groupedCartItems = [];
                        const allItems = uni.getStorageSync('cartItems') || [];
                        const newAllItems = allItems.filter(item => item.phoneNumber!== this.phoneNumber);
                        uni.setStorageSync('cartItems', newAllItems);
                    }
                }
            });
        },
        getStoreSelectedCount(store) {
            return store.goods.filter(item => item.isSelected).length;
        },
        getStoreTotal(store) {
            return store.goods
               .filter(item => item.isSelected)
               .reduce((total, item) => total + (item.price * item.quantity), 0);
        },
        handleStoreCheckout(store) {
            const selectedCount = this.getStoreSelectedCount(store);
            if (selectedCount === 0) {
                uni.showToast({
                    title: '请选择要结算的商品',
                    icon: 'none'
                });
                return;
            }
            const selectedItems = store.goods.filter(item => item.isSelected);
            uni.setStorageSync('selectedCartItems', selectedItems);
            uni.navigateTo({
                url: '/pages/must/must'
            });
        }
    }
};
</script>

<style scoped>
/* 基础样式 */
page {
    height: 100%;
    background-color: #f7f7f7;
}

.page {
    height: 100%;
}

.container {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
}

.scroll-view {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
}

/* 头部样式 */
.cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #fff;
    font-size: 28rpx;
}

.clear-cart {
    color: #666;
}

/* 商品列表样式 */
.goods-list {
    padding-bottom: 20rpx;
}

.goods-item {
    display: flex;
    padding: 25rpx 20rpx;
    margin-bottom: 10rpx;
    background-color: #fff;
}

.item-left {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
}

.goods-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-left: 15rpx;
}

.item-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.goods-info {
    flex: 1;
}

.goods-name {
    font-size: 28rpx;
    color: #333;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.goods-sales {
    font-size: 24rpx;
    color: #999;
    margin: 8rpx 0;
}

.price-box {
    display: flex;
    align-items: center;
}

.current-price {
    font-size: 32rpx;
    color: #e74c3c;
    font-weight: bold;
}

.original-price {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
    margin-left: 10rpx;
}

/* 数量加减器 */
.stepper {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.btn {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
}

.minus {
    background-color: #f5f5f5;
}

.plus {
    background-color: #1b76f6;
    color: #fff;
}

.number {
    margin: 0 20rpx;
    font-size: 28rpx;
    min-width: 40rpx;
    text-align: center;
}

/* 空购物车样式 */
.empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 100rpx;
}

.empty-img {
    width: 300rpx;
    height: 300rpx;
    margin-bottom: 30rpx;
}

.empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
}

.go-shopping {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #1b76f6;
    color: white;
    font-size: 30rpx;
    border-radius: 40rpx;
}

/* 底部结算栏 - 关键样式 */
.footer-bar {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
    z-index: 100;
}

.footer-left {
    display: flex;
    align-items: center;
    flex: 1;
}

.select-text {
    margin: 0 15rpx 0 10rpx;
    font-size: 28rpx;
}

.total-text {
    font-size: 28rpx;
    color: #333;
}

.total-price {
    font-size: 32rpx;
    color: #e74c3c;
    font-weight: bold;
    margin-left: 10rpx;
}

.submit-btn {
    width: 220rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #1b76f6;
    color: white;
    font-size: 30rpx;
    border-radius: 40rpx;
    margin: 0;
    padding: 0;
}

/* 添加店铺相关样式 */
.store-list {
    margin-bottom: 20rpx;
}

.store-item {
    margin-bottom: 20rpx;
    background-color: #fff;
}

.store-header {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
}

.store-select {
    display: flex;
    align-items: center;
}

.select-text {
    font-size: 28rpx;
    color: #333;
    margin-left: 10rpx;
}

.store-name {
    font-size: 28rpx;
    color: #333;
    margin-left: 20rpx;
    font-weight: bold;
}

/* 店铺结算栏样式 */
.store-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background-color: #fff;
    border-top: 1rpx solid #f5f5f5;
}
</style>    